﻿using System;
using System.Linq;
using System.Web;

namespace Quail.Helpers
{
    /// <summary>
    /// Represents a querystring parameter value
    /// </summary>
    public class UrlParameter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UrlParameter"/> class.
        /// </summary>
        /// <param name="url">The url which contains the parameter</param>
        /// <param name="name">The name of the parameter</param>
        public UrlParameter(string url, string name)
            : this(new Uri(url), name)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UrlParameter"/> class.
        /// </summary>
        /// <param name="url">The url which contains the parameter</param>
        /// <param name="name">The name of the parameter</param>
        public UrlParameter(Uri url, string name)
        {
            Name = name;
            RawValue = GetRawValue(url, name);
            Value = HttpUtility.UrlDecode(RawValue);
        }

        /// <summary>
        /// Gets or sets the name of the parameter
        /// </summary>
        public string Name { get; protected set; }

        /// <summary>
        /// Gets or sets the decoded value of the parameter
        /// </summary>
        public string Value { get; protected set; }

        /// <summary>
        /// Gets or sets the unencoded value of the parameter
        /// </summary>
        public string RawValue { get; protected set; }

        /// <summary>
        /// Gets the unencoded value of the parameter from the query string
        /// </summary>
        /// <param name="url">The url which contains the parameter</param>
        /// <param name="name">The name of the parameter</param>
        /// <returns>The unencoded value of the parameter</returns>
        protected static string GetRawValue(Uri url, string name)
        {
            var query = url.Query;
            if (query.StartsWith("?"))
                query = query.Substring(1);
            var urlParams = query.Split('&');
            foreach (var s in urlParams)
            {
                var nvp = s.Split('=');
                if (nvp[0].ToLower() == name.ToLower())
                {
                    var val = nvp.Count() == 2 ? nvp[1] : string.Empty;
                    switch (val)
                    {
                        case "%3E":
                            val = ">";
                            break;
                        default:
                            break;
                    }

                    return val;
                }
            }

            return null;
        }
    }
}
